package com.example.gulimall.common.utils;

import com.example.gulimall.common.enums.ServiceCodeEnum;
import com.example.gulimall.common.exceptions.ApiException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/**
 * @author JGD
 * @since 1.0
 */
@Slf4j
public class WrappedHttpServletRequest extends HttpServletRequestWrapper {
    private byte[] bytes;

    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request The request to wrap
     * @throws IllegalArgumentException if the request is null
     */
    public WrappedHttpServletRequest(HttpServletRequest request) {
        super(request);
        try {
            bytes = toByteArray(request.getInputStream());
        } catch (IOException e) {
            log.error("读取请求参数失败", e);
            throw new ApiException(ServiceCodeEnum.EXPIRE_VERIFY_CODE.getCode(),"非法请求");
        }
    }

    private static byte[] toByteArray(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }

    @Override
    public ServletInputStream getInputStream() {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        return new WrappedServletInputStream(byteArrayInputStream);
    }

    @Override
    public BufferedReader getReader() {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        return new BufferedReader(new InputStreamReader(new WrappedServletInputStream(byteArrayInputStream)));
    }

    private class WrappedServletInputStream extends ServletInputStream {

        private InputStream stream;

        public WrappedServletInputStream(InputStream stream) {
            this.stream = stream;
        }

        @Override
        public int read() throws IOException {
            return stream.read();
        }

        @Override
        public boolean isFinished() {
            return true;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener listener) {

        }
    }
}
